package huffmanTree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13, 7, 8, 3, 29, 6, 1};
        Node root = createHuffmanTree(arr);
        preOrder(root);
    }

    public static Node createHuffmanTree(int[] arr) {
        List<Node> nodes = new ArrayList<Node>();
        for (int v : arr) {
            nodes.add(new Node(v));
        }
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            Node lN=nodes.get(0);
            Node rN=nodes.get(1);
            Node parent=new Node(lN.value+rN.value);
            parent.left=lN;
            parent.right=rN;
            nodes.remove(lN);
            nodes.remove(rN);
            nodes.add(parent);
        }
        return nodes.get(0);
    }
    public static void preOrder(Node root){
        if (root!=null){
            root.preOrder();
        }else{
            System.out.println("是空树，不能遍历");
        }
    }
}

//为了让Node 对象支持Collections集合排序
//让Node 实现 comparable 接口
class Node implements Comparable<Node> {
    int value;
    Node left;
    Node right;

    public void preOrder(){
        System.out.println(this);
        if (this.left!=null){
            this.left.preOrder();
        }
        if (this.right!=null){
            this.right.preOrder();
        }
    }

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        //重小到大
        return this.value - o.value;
    }
}